package com.qf.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.api.CacheFegin;
import com.qf.constant.CacheConstants;
import com.qf.model.StandardSubmit;
import com.qf.service.FilterChainManager;
import com.qf.service.FilterChainService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Map;

@Service
@Slf4j
public class FilterChainManagerImpl implements FilterChainManager {

    @Resource
    private Map<String,FilterChainService> filterChainServiceMap;

    @Resource
    private CacheFegin cacheFegin;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void executeFilter(StandardSubmit standardSubmit) throws Exception {
        Integer clientID = standardSubmit.getClientID();
        String filters =  cacheFegin.hget(CacheConstants.CACHE_PREFIX_CLIENT + clientID, "filters");
        //判空
        if (StringUtils.isEmpty(filters)){
            log.error("[策略模块 - 策略管理员] 无策略可以执行   submit = {}",
                    objectMapper.writeValueAsString(standardSubmit));
            return;
        }

        String[] filterArrays = filters.split(",");

        for (String filter : filterArrays) {
            FilterChainService filterChainService = filterChainServiceMap.get(filter);
            boolean result = filterChainService.strategy(standardSubmit);
            if (!result){
                log.error("[策略模块 - 策略管理员] "+ filter +"策略执行失败   submit = {}",
                        objectMapper.writeValueAsString(standardSubmit));



                return;
            }
        }


    }
}
